/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fmsactionserver.server;

import fmsactionserver.server.inetclient.InetRefresher;
import fmsactionserver.server.logger.logGui.LogFrame;
import fmsactionserver.server.logger.InputLogger;
import fmsactionserver.server.settings.actions.SettingsFrame;
import fmsactionserver.server.settings.actions.data.ActionSettingsCollector;
import fmsactionserver.server.settings.input.InputSettings;
import fmsactionserver.server.settings.input.InputSettingsFrame;
import java.awt.AWTException;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author rbs
 */
public class FMSActionServer {

    InputLogger logger = new InputLogger();
    ActionSettingsCollector settings = new ActionSettingsCollector();
    InputSettings inputSettings;
    
    private Boolean syncOn = false; 
    private Timer timer = new Timer();

    public FMSActionServer(Boolean gui){
    

        if (gui)
        {
            SystemTray tray = SystemTray.getSystemTray();

            final String dir = getProgramPath();

            // LOAD FROM FILE:
            //TODO: Same Save-System for both settings
            if (new File("inputsettings").exists())
                this.inputSettings = InputSettings.readFromFile();
            else
                this.inputSettings = null;
            
            File file = new File(dir  + "settings");
            ObjectInputStream inputStream = null;
            if (file.exists()) {
                try {
                    inputStream = new ObjectInputStream(new FileInputStream(file));
                    settings = (ActionSettingsCollector) inputStream.readObject();
                    inputStream.close();
                } catch (Exception ex) {
                    try {
                        //Settings file incompatible
                        inputStream.close();
                    } catch (IOException ex1) {
                        Logger.getLogger(FMSActionServer.class.getName()).log(Level.SEVERE, null, ex1);
                    }
                    //warn user:
                    JOptionPane.showMessageDialog(null, "Achtung:\n Die vorhandene Settings-Datei ist nicht mehr "
                            + "mit dieser Version des Programms kompatibel.\n"
                            + "Ein Backup wird unter dem Name settings_old angelegt.", "Alte Einstellungen nicht kompatibel", JOptionPane.WARNING_MESSAGE);

                    //wenn backup schon existiert, dann löschen:
                    File backup_file = new File(dir + "settings_old");
                    if (backup_file.exists())
                        backup_file.delete();

                    //backup erstellen:
                    if (!file.renameTo(backup_file))
                        System.out.println("Error renaming to " + backup_file.getName());
                }
            }
        
            final ActionSettingsCollector finSettings = settings;
        
            TrayIcon icon = new TrayIcon(new ImageIcon(getClass().getResource("ico.png")).getImage(), "FMSActionServer");
            icon.setImageAutoSize(true);

            PopupMenu menu = new PopupMenu("FMSActionServer");


            MenuItem exitItem = new MenuItem("Beenden");
            exitItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });

            MenuItem actionSettingsItem = new MenuItem("Aktionen");

            actionSettingsItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    new SettingsFrame(dir, finSettings);
                }
            });
            
            MenuItem settingsItem = new MenuItem("Einstellungen");
            
            settingsItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    new InputSettingsFrame(inputSettings);
                }
            });

            MenuItem logItem = new MenuItem("Log");

            logItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    new LogFrame(logger);
                }
            });
            
            MenuItem syncItem = new MenuItem("Synchronisieren");

            syncItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    Timer timer = new Timer();
                    timer.schedule(new InetRefresher(inputSettings, logger), 0);
                }
            });
            
            final MenuItem autoSyncItem = new MenuItem("[ ]Synch. alle 2 s");

            autoSyncItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (!syncOn)
                    {
                        timer.schedule(new InetRefresher(inputSettings, logger), 0, 2000);
                        autoSyncItem.setLabel("[X] Synch. alle 2 s");
                    }
                    else
                    {
                        timer.cancel();
                        autoSyncItem.setLabel("[ ] Synch. alle 2 s");
                    }
                        
                    
                }
            });
            
            menu.add(exitItem);
            menu.add(actionSettingsItem);
            menu.add(settingsItem);
            menu.add(logItem);
            menu.add(syncItem);
            menu.add(autoSyncItem);
            icon.setPopupMenu(menu);
            try {
                tray.add(icon);
            } catch (AWTException ex) {
                Logger.getLogger(FMSActionServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        if (inputSettings.getType() == InputSettings.InputSettingType.FMS32)
        {
            try {
                InputServer inputListener = new InputServer(this, logger);
                inputListener.start();
            } catch (IOException ex) {
                Logger.getLogger(FMSActionServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        ShareServer shareServer;
        try {
            if (!gui)
                shareServer = new ShareServer(logger);
        } catch (IOException ex) {
            Logger.getLogger(FMSActionServer.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public ActionSettingsCollector getSettings() {
        return settings;
    }
    
    public static String getProgramPath() {
        
        File file = new File(FMSActionServer.class.getProtectionDomain().getCodeSource().getLocation().toString());
        System.out.println("Path: "  +  file.getPath());
        return file.getPath() + File.separator;
    }
    
}
